#include <stdio.h>
#include <stdlib.h>
#include "Bowling.h"

Bowling::Bowling()
{
	score = 0;
	currentRoll = 0;
	for (int i=0;i<sizeof(rolls)/sizeof(rolls[0]);i++)
		rolls[i]=0;
	for (int i=0;i<FRAMES_NUM;i++){
		bounsCount[i] = 0;
	}
	isInBonusRoll = FALSE;
	isGameOver = FALSE;
}

Bowling::~Bowling(){

}

int RollToFrameIndex(int rollIndex){
	return rollIndex/2;
}

int RollToIndexInFrame(int rollIndex){
	return rollIndex%2;
}

void Bowling::checkSpare(){
	if (RollToIndexInFrame(currentRoll)==1) //last roll in a frame
	{
		if (rolls[currentRoll] + rolls[currentRoll-1]==10)
		{
			bounsCount[currentRoll/2]  = 1;
		}
	}
}

void Bowling::checkStrike(){
	if (rolls[currentRoll]==10 && currentRoll<20){
		bounsCount[RollToFrameIndex(currentRoll)] = 2;
	}
}

void Bowling::moveToNextRoll(){
	if ((currentRoll%2)==0 && rolls[currentRoll]==10) //first roll in a frame and is a strike
	{
		currentRoll++; //skip to next frame
	}
	currentRoll++;
	if (currentRoll>=20)
	{

		if (bounsCount[FRAMES_NUM-1]>0 ||bounsCount[FRAMES_NUM-2]>0)
		{
			isInBonusRoll=TRUE;
			isGameOver = FALSE;
		}
		else
		{
			isGameOver = TRUE;
			isInBonusRoll=FALSE;
		}
	}
}

void Bowling::addBonus(){
	for (int i=0;i<10;i++){
		if (bounsCount[i] >0)
		{
			score +=rolls[currentRoll];
			bounsCount[i]--;
		}
	}
}

void Bowling::addScore(){
	score+=rolls[currentRoll];
}

void Bowling::roll(int pins){
	rolls[currentRoll]=pins;
	if (currentRoll<20)
		addScore();
	addBonus();
	checkSpare();
	checkStrike();
	moveToNextRoll();
}
